package cn.shanke.torrentmanagerserver.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @author shanke
 */
public class JWTUtil {

    public final static String SECRET = "tmawesome!";

    /**
     * 校验token是否正确
     * @param token 密钥
     * @param passkey 密码
     * @return 是否正确
     */
    public static boolean verify(String token, String passkey) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("passkey", passkey)
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的密码
     */
    public static String getPasskey(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("passkey").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,指定时间后过期,一经生成不可修改，令牌在指定时间内一直有效
     *
     * @param passkey
     * @return 加密的token
     */
    public static String sign(String passkey) {
        return sign(passkey, null);
    }

    /**
     *
     * @param passkey
     * @param expireTime
     * @return
     */
    public static String sign(String passkey, Long expireTime) {
        // 附带密码信息
        JWTCreator.Builder builder = JWT.create()
                .withClaim("passkey", passkey);
        if (expireTime != null && expireTime > 0) {
            builder.withExpiresAt(new Date(System.currentTimeMillis() + expireTime));
        }
        return builder.sign(Algorithm.HMAC256(SECRET));
    }
}
